﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Membership.OpenAuth;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Authy.Net;

namespace MFAAuthyTest.Account
{
    public partial class Register : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {          
            RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
        }

        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
            // for a real storage account:
            String dataConnectionString = "DefaultEndpointsProtocol=https;AccountName=aliciaauthy;AccountKey=UihKsy9AYk9R/UFMhpnxs9Ju459H+BVaUROJ5SJuGL7M2y8ILV8QwmeEK1gw+ga+AYwcF9nMjq5VPsztoGHT1Q==";
            String tableName = "authy";
            CloudStorageAccount account = CloudStorageAccount.Parse(dataConnectionString);
            // create the table client
            CloudTableClient tableClient = account.CreateCloudTableClient();
            // create the table if it doesn't exist
            CloudTable table = tableClient.GetTableReference(tableName);

            var client = new AuthyClient("9d757c049978d32651d0e11e801b36f2", test: false);
            RegisterUserResult authyID = client.RegisterUser(RegisterUser.Email, RegisterUser.Answer, 00353);
            FormsAuthentication.SetAuthCookie(RegisterUser.UserName, createPersistentCookie: false);

            TableEntity entry = new TableEntity(RegisterUser.UserName, authyID.UserId);
            TableOperation addOperation = TableOperation.Insert(entry);       // Insert listing given in function parameters
            table.Execute(addOperation);

            string continueUrl = RegisterUser.ContinueDestinationPageUrl;
            if (!OpenAuth.IsLocalUrl(continueUrl))
            {
                continueUrl = "~/Account/Manage";
            }
            Response.Redirect(continueUrl);
        }
    }
}